package com.cz.nongyetongv5.utils;

import android.util.Log;

import com.cz.nongyetongv5.bean.User;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * ���板��ュ�
 */
public class HttpUtils {

    /**
     * 娑濠绱剁灞惧
     */
    public static final int SUCCESS = 200;

    /**
     * 娑濠绱堕ㄥ��缂婊��锟
     */
    public static final int NETWORK_ERR = -1;

    /**
     * 娑濠绱剁���
     */
    public static final int TIMEOUT = -2;

    /**
     * ���¢挎���
     */
    public static final int UNKNOWERROR = -3;

    /**
     * 姒妯款婚ㄥ�harset
     */
    private static final String CHARSET = "UTF-8";

    private static final int TIMEOUT_CONFIG = 60 * 1000;

    /**
     * 瑜版诡�Ч���存�
     */
    public interface OnRequestExecuted {

        public void onRequestExecuted(int responseCode, String responseBody);
    }

    private static HttpUtils httpUtils;

    private OnRequestExecuted onRequestExecuted;

    public HttpUtils() {

    }

    /**
     * ��绶ュΟ�ü崇础�惧嘲褰娑濠绱跺��ュ
     *
     * @return
     */
    public static HttpUtils getInstance() {
        if (null == httpUtils) {
            httpUtils = new HttpUtils();

        }
        return httpUtils;
    }

    /**
     * ��х娑濠绱剁ü瑰本��搴ｆ��ョ剁��ユ
     */
    public void setOnRequestExecuted(OnRequestExecuted onRequestExecuted) {
        this.onRequestExecuted = onRequestExecuted;
    }

    /**
     * @param requestUrl   �锟界��伴︽挎�
     * @param method       : ���伴ㄥ�瀵�拷
     * @param charset      : 缂� �
     * @param authUserName : 妤 宀���扮础�ㄥ�ら村嘲�
     * @param authPassword : 妤 宀���扮础�ㄥ����
     * @return
     * @throws IOException
     * @para : ���
     */
    public void sendRequest(String requestUrl, String data, String method,
                            String charset, String authUserName, String authPassword, User user) {

        // 婵″�charset ������
        if (!CharsetUtil.isNotNull(data)) {
            // ��х娑娲�帛��娈charset
            charset = CHARSET;
        }

        // �惧嘲绶�httpClient�ü电��
        DefaultHttpClient client = new DefaultHttpClient();

        client.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONFIG);

        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                TIMEOUT_CONFIG);

        // ���扮纭�
        HttpUriRequest request = null;

        // �宥绨茬纭�
        HttpResponse response = null;

        int requestCode = HttpUtils.UNKNOWERROR;

        // �宥濮�ｃㄧ��ョ垫���宓
        String responseBody = null;

        try {

            if (authUserName != null && authPassword != null) {

                // ��х���
                Credentials defaultcreds = new UsernamePasswordCredentials(
                        authUserName, authPassword);

                client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                        defaultcreds);

            }

            // 婵″����ost���
            if ("post".equalsIgnoreCase(method)) {

                request = new HttpPost();

                ((HttpPost) request).setURI(new URI(requestUrl));

                // ��х���
                ((HttpPost) request).setHeader("Content-Type",
                        "application/json");

                StringEntity entity = new StringEntity(data, charset);

                ((HttpPost) request).setEntity(entity);

            } else {
                // get��扮础����
                request = new HttpGet();

                if (user != null) {

                    if (authPassword != null && authUserName != null) {

                        if (requestUrl.endsWith("/")) {

                            requestUrl += "username/" + user.getUsername();

                        } else {

                            requestUrl += "/username/" + user.getUsername();
                        }
                    }

                } else {
                    if (authPassword != null && authUserName != null) {
                        if (requestUrl.endsWith("/")) {

                            requestUrl += "username/zyz";

                        } else {

                            requestUrl += "/username/zyz";
                        }
                    }
                }

                if (authPassword != null && authUserName != null) {
                    if (requestUrl.endsWith("/")) {

                        requestUrl += "from/1";

                    } else {

                        requestUrl += "/from/1";
                    }
                }

                ((HttpGet) request).setURI(new URI(requestUrl));
            }

            if (request instanceof HttpGet) {

                // �惧嘲绶辨╂挎��ü电��
                response = client.execute(((HttpGet) request));

            } else if (request instanceof HttpPost) {

                response = client.execute(((HttpPost) request));
            }

            // �锝�ü界��扮�锟�
            requestCode = response.getStatusLine().getStatusCode();

            responseBody = EntityUtils.toString(response.getEntity());

        } catch (MalformedURLException e) {
            // URL�锝�ü介挎���
            requestCode = HttpUtils.UNKNOWERROR;
        } catch (ProtocolException e) {
            // Tcp �挎��
            requestCode = HttpUtils.UNKNOWERROR;
        } catch (SocketTimeoutException e) {
            // �╃村复�����垮�缍
            requestCode = HttpUtils.TIMEOUT;
        } catch (IOException e) {
            // IO 瀵��
            requestCode = HttpUtils.NETWORK_ERR;
        } catch (URISyntaxException e) {
            // URL�锝�ü介挎���
            requestCode = HttpUtils.UNKNOWERROR;
        } finally {
            // 濞���у�爱
            client.getConnectionManager().shutdown();
        }

        // �笛��ョ剁��ユ
        if (onRequestExecuted != null) {
            onRequestExecuted.onRequestExecuted(requestCode, responseBody);
        }

    }

    public void sendRequest(String requestUrl, String data, String method,
                            String charset, User user) {

        if (!CharsetUtil.isNotNull(data)) {
            charset = CHARSET;
        }

        DefaultHttpClient client = new DefaultHttpClient();

        client.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONFIG);

        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                TIMEOUT_CONFIG);

        // ���扮纭�
        HttpPost request = null;

        // �宥绨茬纭�
        HttpResponse response = null;

        int requestCode = HttpUtils.UNKNOWERROR;

        String responseBody = null;

        try {
            Log.d("v0917_sample_post_url", requestUrl);
            request = new HttpPost();
            request.setURI(new URI(requestUrl));
            request.setHeader("Content-Type", "text/xml;charset=utf-8");

            Log.d("v0917_sample_post_data", data);
            StringEntity entity = new StringEntity(data, "UTF-8");

            ((HttpPost) request).setEntity(entity);

            response = client.execute(((HttpPost) request));

            requestCode = response.getStatusLine().getStatusCode();

            responseBody = EntityUtils.toString(response.getEntity());

        } catch (MalformedURLException e) {
            // URL�锝�ü介挎���
            requestCode = HttpUtils.UNKNOWERROR;
        } catch (ProtocolException e) {

            requestCode = HttpUtils.UNKNOWERROR;
        } catch (SocketTimeoutException e) {
            // �╃村复�����垮�缍
            requestCode = HttpUtils.TIMEOUT;
        } catch (IOException e) {
            // IO 瀵��
            requestCode = HttpUtils.NETWORK_ERR;
        } catch (URISyntaxException e) {
            // URL�锝�ü介挎���
            requestCode = HttpUtils.UNKNOWERROR;
        } finally {
            // 濞���у�爱
            client.getConnectionManager().shutdown();
        }

        // �笛��ョ剁��ユ
        if (onRequestExecuted != null) {
            onRequestExecuted.onRequestExecuted(requestCode, responseBody);
        }

    }

}
